package com.demo.controller;

import com.alibaba.fastjson.JSON;
import com.demo.dto.GatewayReq;
import com.demo.dto.GeneralResult;
import com.demo.miya.controller.client.MiyaClient;
import com.demo.miya.controller.client.MiyaHelloClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 测试链接： http://localhost:8763/service/hi?name=forezp
 *
 * Spring Bean重新初始化并载入新的配置内容，修改配置文件后不用重启服务重新加载
 * 需要动态更新配置信息，只要在提供服务的类添加@RefreshScope
 * @author K
 *
 */
@Slf4j
@RestController
@RefreshScope
public class ServicController {

	private final AtomicInteger atomicInteger = new AtomicInteger();

	@Value("${server.port}")
	String port;

	/**
	 *  读取配置中心属性
 	 */
	@Value("${foo}")
	String foo;

	@Resource
	private MiyaClient miyaClient;
	@Resource
	private MiyaHelloClient miyaHelloClient;

	/**
	 * 测试读取配置中心的配置
 	 */
	@PostMapping("/service/hi")
	public String hi(@RequestParam String name) {
		String hi = "hi " + name + ",i am from port:" + port + ", config:" + foo;
		log.info("/hi服务：{}", hi);
		return hi;
	}

	@GetMapping("/service/info")
    public String info(){
		log.info("servic-hi服务info1接口被调用,调用次数：{}", atomicInteger.incrementAndGet());
		return "i'm service-hi info " + new Date();
    }

	@GetMapping("/service/info/name")
	public String info(@RequestParam("name") String name){
		log.info("servic-hi服务info/name接口被调用,调用次数：{}", atomicInteger.incrementAndGet());
		return "i'm service-hi info, name is " + name;
	}

	@PostMapping("/service/testGateway")
	public GeneralResult<GatewayReq> testGateway(@RequestBody GatewayReq gatewayReq) {
		log.info("testGateWay 入参：{}", JSON.toJSONString(gatewayReq));
		return GeneralResult.success(gatewayReq);
	}

	/**
	 * 必须启动 miya 服务
	 * 引用miyaClient包，采用类似RPC方式调用
	 * @return String
	 */
	@GetMapping("/service/miyaHi")
	public String miyaHi() {
		log.info("调用miyaClient");
		return miyaClient.hi();
	}

	/**
	 * 必须启动 miya 服务
	 * 引用miyaClient包，采用类似RPC方式调用
	 * @return String
	 */
	@GetMapping("/service/miyaHello")
	public String miyaHello() {
		log.info("调用miyaHelloClient");
		return miyaHelloClient.hello();
	}
}
